/*
 *  GUI.cpp
 *  Rempart
 *
 *
 */

#include "GUI.h"

extern sf::Mutex globalLock;

GUI* GUI::instance(0);

GUI * GUI::getInstance() {
	
	if (instance == 0) {
		instance = new GUI();
	}
	return instance;
}


GUI::GUI(){
	this->loop = true;
	this->Create(sf::VideoMode(GUI::width, GUI::heigth), "Remparts", sf::Style::Close);
	this->elapsedTime = 0;
	this->drawLayers.push_back(new Menu());
	this->drawLayers.push_back(Map::getInstance());
	
	
	
#ifdef DEBUG
	this->drawLayers.push_back(DebugTools::getInstance());
	this->framerateDisplay = new sf::String();
	this->framerateDisplay->SetSize(12);
	this->framerateDisplay->SetColor(sf::Color::White);
	this->framerateDisplay->SetPosition(GUI::width-120,GUI::heigth-20);
	this->drawLayers.push_back(this->framerateDisplay);
#endif	

	
	this->SetFramerateLimit(60);
	

}


void GUI::startLoop(){

#ifdef DEBUG
	char framerateDisplayText[21]; // prevoir la place pour \0 
#endif
	this->ShowMouseCursor(false);
	sf::Clock clock;
	EventManager::getInstance()->Launch();

    while (this->IsOpened()){
		if (this->loop) {
		
			this->elapsedTime = clock.GetElapsedTime();

			sf::Event Event;
		
			if(this->GetEvent(Event)){

				if (Event.Type == sf::Event::Closed)
					this->Close();
			

				if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
					this->Close();
			}
		

		
		#ifdef DEBUG
			sprintf(framerateDisplayText, "Framerate: %f",1.f / this->GetFrameTime());
			this->framerateDisplay->SetText(framerateDisplayText);
		#endif	
			
			globalLock.Lock();
			this->Clear();
		
			for (int i = 0; i < this->drawLayers.size(); i++) {
				this->Draw(*this->drawLayers[i]);
			}
			
			if (NotificationsManager::getInstance()->isVisible()) {
				Draw(*NotificationsManager::getInstance());
			}
			
			this->Draw(*Cursor::getInstance());
			this->Display();
			globalLock.Unlock();
		}
	
		else {
			sf::Sleep(5);
		}
	}
	
		
}	
	


GUI::~GUI(){
	globalLock.Lock();
	
	EventManager::getInstance()->stopLoop();
	EventManager::getInstance()->Wait();
	delete EventManager::getInstance();
	for (int i = 0; i < this->drawLayers.size(); i++) {
		delete this->drawLayers[i];
	}
	delete RessourcesManager::getInstance();
	printf("GUI supprimée\n");
	globalLock.Unlock();
}



void GUI::stopLoop(){
	this->loop=false;
}
